//
//  ReadImageDataManager.m
//  YuanXinCamera
//
//  Created by 晏德智 on 2016/10/25.
//  Copyright © 2016年 晏德智. All rights reserved.
//

#import "ReadImageDataManager.h"
#import <React/RCTImageLoader.h>
#import "ReadImageInfo.h"
#import <RCTConvert+ReadImage.h>

@implementation ReadImageDataManager

RCT_EXPORT_MODULE();

@synthesize bridge = _bridge;
@synthesize methodQueue = _methodQueue;

- (dispatch_queue_t)methodQueue
{
    if(!_methodQueue){
        _methodQueue= dispatch_queue_create("YuanXinReadImage.Queue",DISPATCH_QUEUE_CONCURRENT);
        //DISPATCH_QUEUE_CONCURRENT DISPATCH_QUEUE_SERIAL
        //_methodQueue = dispatch_queue_create("com.ReadImageData", DISPATCH_QUEUE_SERIAL);
    }
    return _methodQueue;
}


RCT_EXPORT_METHOD(readImage:(ReadImageInfo *)imageInfo resolver:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject){
    
    __block RCTPromiseResolveBlock  successBlock = nil;
    if(resolve){
        successBlock =[resolve copy];
    }
    __block RCTPromiseRejectBlock  errorBlock = nil;
    if(reject){
        errorBlock=  [reject copy];
    }
    
    
    [_bridge.imageLoader loadImageWithURLRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:imageInfo.filePath ]] size:imageInfo.size scale:imageInfo.scale clipped:YES resizeMode:RCTResizeModeStretch progressBlock:^(int64_t progress, int64_t total) {
        
    } partialLoadBlock:^(UIImage *image) {
        
    } completionBlock:^(NSError *error, UIImage *image) {
        if (error) {
            errorBlock([@(error.code) stringValue],error.description,error);
            return ;
        }
        
        if(successBlock){
            NSData *imageData = UIImageJPEGRepresentation(image, imageInfo.scale);
            //[image dataByCompressToScale:1.0 toQuality:imageInfo.scale];
            /*
             if (UIImagePNGRepresentation(image)) {
             imageData = UIImagePNGRepresentation(image);
             } else {
             imageData = UIImageJPEGRepresentation(image, 1.0);
             }
             */
            
            NSString *base64Encoded = [imageData base64EncodedStringWithOptions:0];
            successBlock(@{@"filePath":imageInfo.filePath,@"objectKey":imageInfo.objectKey,@"imageData":base64Encoded});
        }
        
    }];
}


RCT_EXPORT_METHOD(readImages:(NSArray<ReadImageInfo *> *)items resolver:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject)
{
    __block RCTPromiseResolveBlock  successBlock = nil;
    if(resolve){
        successBlock =[resolve copy];
    }
    __block RCTPromiseRejectBlock  errorBlock = nil;
    if(reject){
        errorBlock=  [reject copy];
    }
    
    
    __block NSMutableArray *result = [NSMutableArray new];
    
    int count =  items.count;
    
    dispatch_group_t group = dispatch_group_create();
    
    //dispatch_apply能避免线程爆炸
    __weak typeof(self) weakSelf = self;
    
    dispatch_apply(count, self.methodQueue, ^(size_t i){
        NSLog(@"correct %zu",i);
        __block ReadImageInfo *item =  items[i];
        dispatch_group_enter(group);
        
        [weakSelf.bridge.imageLoader loadImageWithURLRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:item.filePath ]] size:item.size scale:item.scale clipped:YES resizeMode:RCTResizeModeStretch progressBlock:^(int64_t progress, int64_t total) {
            
        } partialLoadBlock:^(UIImage *image) {
            
        } completionBlock:^(NSError *error, UIImage *image) {
            if (error) {
                errorBlock([@(error.code) stringValue],error.description,error);
                dispatch_group_leave(group);
                return ;
            }
            NSData *imageData = UIImageJPEGRepresentation(image, item.scale);
            /*
             if (UIImagePNGRepresentation(image)) {
             imageData = UIImagePNGRepresentation(image);
             } else {
             imageData = UIImageJPEGRepresentation(image, item.scale);
             }
             */
            NSString *base64Encoded = [imageData base64EncodedStringWithOptions:0];
            [result addObject: @{@"filePath":item.filePath,@"imageData":base64Encoded}];
            dispatch_group_leave(group);
        }];
    });
    
    dispatch_group_notify(group, self.methodQueue,^{
        if(successBlock){
            successBlock(result);
        }
    });
    
}

@end
